
import face_recognition
import cv2
import requests
import pyttsx3
import json
from train import known_names
from train import known_encodings

taskId = 2
cap = cv2.VideoCapture(0)
process_this_frame = True
continue_loop = True
face_count = 0
name_counts = {}
known_faces_list = []
while continue_loop:
    # 逐帧捕获
    ret, frame = cap.read()
    flag = cv2.waitKey(1)
    # opencv的图像是BGR格式的，而我们需要是的RGB格式的，因此需要进行一个转换。
    rgb_frame = frame[:, :, ::-1]
    if process_this_frame:
        face_locations = face_recognition.face_locations(rgb_frame)  # 获得所有人脸位置
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)  # 获得人脸特征值
        face_names = []  # 存储出现在画面中人脸的名字
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_encodings, face_encoding, tolerance=0.5)
            if True in matches:
                first_match_index = matches.index(True)
                name = known_names[first_match_index]
            else:
                name = "unknown"
            face_names.append(name)
    process_this_frame = not process_this_frame

    # 将捕捉到的人脸显示出来
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)  # 画人脸矩形框
        # 加上人名标签
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        cv2.imshow('frame', frame)
        for name in face_names:
            known_faces_list.append(name)  # 将当前帧的人脸名称添加到列表中
            if name in name_counts:
                name_counts[name] += 1
            else:
                name_counts[name] = 1

        face_count += 1
        if face_count == 50:
            max_count_name = max(name_counts, key=name_counts.get)  # 获取出现次数最多的名字
            print(f"出现次数最多的名字是：{max_count_name}")
            for i in range(0, 1):
                #time.sleep(10)
                flag = 27
            if flag == 27:  # 按下ESC键时
                if len(face_names) == 0:
                    print("未检测到人脸")
                elif max_count_name == "unknown":
                    print("陌生人脸")
                else:
                    print(max_count_name)
                    print("已识别到人脸")
                    print("正在发送请求")
                    #print("请求成功+语音播放")
                    url = "http://localhost:8080/camera/processFaceRecogData"  # 这里需要后端服务器地址
                    data = {"taskId": taskId, "studentId": max_count_name}
                    # print(data)
                    headers = {'Content-Type': 'application/json'}
                    response = requests.post(url, json=data, headers=headers)
                    # print(response.status_code)
                    if response.status_code == 200:
                        print("请求成功")
                    else:
                        print("请求失败")
                    print(response.text)
                    # 将 JSON 字符串解析为 Python 字典
                    json_data = json.loads(response.text)
                    # 获取 "message" 对应的值
                    message_value = json_data['message']
                    engine = pyttsx3.init()
                    if message_value == "成功识别":
                        engine.say("已成功！下一位！")
                        # engine.runAndWait()
                    else:
                        engine.say("已识别！请离开！")
                        # engine.runAndWait()
                    engine.runAndWait()
                    # 清空已知人脸列表和名字计数字典
                    known_faces_list.clear()
                    name_counts.clear()
                    face_count = 0  # 重置计数器
                    print("识别已暂停，按 'R' 键恢复或按其他任意键退出")
                    while True:
                        key_pressed = cv2.waitKey(1)  # 等待用户按键
                        if key_pressed == ord('R') or key_pressed == ord('r'):  # 检查是否按下'R'键
                            print("识别恢复中...")
                            break  # 跳出等待子循环并重新开始主循环
                        elif key_pressed != -1:  # 其他任意键被按下
                            continue_loop = False  # 设置标志位以结束主循环
                            break  # 跳出等待子循环
            else:
                break

# 一切完成后，释放捕获
cap.release()
cv2.destroyAllWindows()

